package controllers

import (
	"myerp/models"
	"strconv"
	"time"
)

type SortsController struct {
	CommonController
}

//添加分类
func (c *SortsController) Add() {
	if c.Ctx.Request.Method == "POST" {
		reData := make(map[string]interface{})
		reData["status"] = 1
		var md models.Sorts
		md.Name = c.GetString("name")
		md.Pid, _ = c.GetInt("pid", 0)
		md.Ctime = int(time.Now().Unix())
		_, err := models.AddSorts(&md)
		if err != nil {
			reData["msg"] = "添加分类失败！"
		} else {
			reData["url"] = "/sorts/list"
			reData["status"] = 1
		}
		c.Data["json"] = reData
		c.ServeJSON()
	}
	//获取以及分类
	l, _ := models.GetAllSortsByPid(0)
	c.Data["ActionName"] = "添加分类"
	c.Data["ol"] = l

	c.Layout = "base.html"
	c.TplName = "sorts/add.html"
}

//列表
func (c *SortsController) List() {
	pid, _ := c.GetInt("pid", 0)
	l, _ := models.GetAllSortsByPid(pid)
	c.Data["ActionName"] = "分类列表"
	c.Data["List"] = l
	c.Layout = "base.html"
	c.TplName = "sorts/list.html"

}

//删除分类
func (c *SortsController) Delete() {
	Id := c.GetString("id")
	resId, _ := strconv.Atoi(Id)
	err := models.DeleteSorts(resId)
	reData := make(map[string]interface{})
	reData["status"] = 0
	reData["msg"] = "删除失败！"
	if err == nil {
		reData["status"] = 1
		reData["msg"] = "删除成功"
	}
	c.Data["json"] = reData
	c.ServeJSON()
}

//js获取列表
func (c *SortsController) Ajaxlist() {
	reData := make(map[string]interface{})
	reData["status"] = 0
	pid, err := c.GetInt("pid")
	if err != nil || pid < 1 {
		reData["tl"] = ""
		c.Data["json"] = reData
		c.ServeJSON()
		return
	}
	l, _ := models.GetAllSortsByPid(pid)
	reData["tl"] = l
	reData["status"] = 1
	c.Data["json"] = reData
	c.ServeJSON()
}

//编辑
func (c *SortsController) Edite() {
	var id int
	if c.Ctx.Request.Method == "POST" {
		reData := make(map[string]interface{})
		reData["status"] = 0
		var md models.Sorts
		id, err := c.GetInt("id")
		if err != nil {
			reData["msg"] = "修改的分类不存在！"
			c.Data["json"] = reData
			c.ServeJSON()
			return
		}
		md.Id = id
		md.Name = c.GetString("name")
		md.Pid, _ = c.GetInt("pid", 0)
		err = models.UpdateSortsById(&md)
		if err != nil {
			reData["msg"] = "修改分类失败"
		} else {
			reData["status"] = 1
			reData["url"] = "/sorts/list"
		}
		c.Data["json"] = reData
		c.ServeJSON()
		return
	}

	id, err := c.GetInt("id")
	if err != nil {
		c.Redirect("/sorts/list", 302)
		return
	}
	sd, err := models.GetSortsById(id)
	if err != nil {
		c.Redirect("/sorts/list", 302)
		return
	}
	l, _ := models.GetAllSortsByPid(sd.Pid)
	c.Data["ol"] = l
	c.Data["Sdata"] = sd
	c.Layout = "base.html"
	c.TplName = "sorts/edite.html"

}
